import {
  Tile as TileLayer,
  Vector as VectorLayer,
  Group as LayerGroup,
} from "ol/layer";
import { XYZ, WMTS } from "ol/source";
import { get as getProjection } from "ol/proj";
import { getWidth, getTopLeft } from "ol/extent";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import WMTSCapabilities from "ol/format/WMTSCapabilities.js";
import { optionsFromCapabilities } from "ol/source/WMTS.js";

import { addLayers /**批量添加图层的方法 */ } from "./layer";
import { setProjection /**设置投影的方法 */ } from "./view";

/**
 * @description  添加天地图底图
 * @param {*} map  地图对象
 * @param {string} token  天地图API token
 * @param {'vec'|'img'|'ter'} layerType  图层类型 ,可选值：'vec'|'img'|'ter'
 *   'vec'：矢量图层，'img'：影像图层，'ter'：地形图层
 * @param {'w'|'c'} projKey  投影类型,可选值：'w'|'c'
 *   'w'：球面墨卡托投影，'c'：经纬度投影
 * @param {'xyz'|'wmts'} service  底图服务类型,可选值：'xyz'|'wmts'
 *   'xyz'：使用XYZ协议，'wmts'：使用WMTS协议
 */
export const addTdtBaseLayer = (
  token,
  layerType,
  projKey = "w",
  service = "xyz"
) => {
  let baseLayer,
    markLayer,
    title =
      layerType === "vec" ? "矢量" : layerType === "img" ? "影像" : "地形",
    markKey = `c${layerType.charAt(0)}a`;

  if (service === "xyz") {
    baseLayer = new TileLayer({
      properties: {
        id: `tdt_${layerType}_${projKey}`,
        name: `天地图${title}底图`,
      },
      source: new XYZ({
        url: `http://t{0-7}.tianditu.gov.cn/DataServer?T=${layerType}_${projKey}&x={x}&y={y}&l={z}&tk=${token}`,
        projection: projKey === "w" ? "EPSG:3857" : "EPSG:4326",
      }),
    });

    markLayer = new TileLayer({
      properties: {
        id: `tdt_${markKey}_${projKey}`,
        name: `天地图${title}注记`,
      },
      source: new XYZ({
        url:
          `http://t{0-7}.tianditu.gov.cn/DataServer?T=${markKey}_${projKey}&x={x}&y={y}&l={z}&tk=` +
          token,
        projection: projKey === "w" ? "EPSG:3857" : "EPSG:4326",
      }),
    });
  } else if (service === "wmts") {
    const projection = getProjection(
      projKey === "w" ? "EPSG:3857" : "EPSG:4326"
    ); // 获取投影
    const projectionExtent = projection.getExtent(); // 获取地理范围
    const size = getWidth(projectionExtent) / 256; // 获取分辨率
    const resolutions = [];
    const matrixIds = [];
    for (let z = 0; z < 19; ++z) {
      resolutions[z] = size / Math.pow(2, z);
      matrixIds[z] = z;
    }

    const tileGrid = new WMTSTileGrid({
      origin: getTopLeft(projectionExtent),
      resolutions: resolutions,
      matrixIds: matrixIds,
    });

    baseLayer = new TileLayer({
      properties: {
        id: `tdt_${layerType}_${projKey}`,
        name: `天地图${title}底图`,
      },
      source: new WMTS({
        url: `http://t{0-6}.tianditu.gov.cn/${layerType}_${projKey}/wmts?tk=${token}`,
        projection,
        layer: layerType,
        matrixSet: projKey,
        style: "default",
        wrapX: true,

        tileGrid,
        // tileLoadFunction: (imageTile, src) => {
        //   // 使用滤镜 将白色修改为深色
        //   let img = new Image();
        //   // img.crossOrigin = ''
        //   // 设置图片不从缓存取，从缓存取可能会出现跨域，导致加载失败
        //   img.setAttribute("crossOrigin", "anonymous");
        //   img.onload = () => {
        //     let canvas = document.createElement("canvas");
        //     let w = img.width;
        //     let h = img.height;
        //     canvas.width = w;
        //     canvas.height = h;
        //     let context = canvas.getContext("2d");
        //     context.filter =
        //       "grayscale(98%) invert(100%) sepia(20%) hue-rotate(180deg) saturate(1600%) brightness(120%) contrast(90%)";
        //     context.drawImage(img, 0, 0, w, h, 0, 0, w, h);
        //     imageTile.getImage().src = canvas.toDataURL("image/png");
        //   };
        //   img.onerror = () => {
        //     imageTile.getImage().src = require("@/assets/logo.png");
        //   };
        //   img.src = src;
        // },
      }),
    });

    markLayer = new TileLayer({
      properties: {
        id: `tdt_${markKey}_${projKey}`,
        name: `天地图${title}注记`,
      },
      source: new WMTS({
        url: `http://t{0-6}.tianditu.gov.cn/${markKey}_${projKey}/wmts?tk=${token}`,
        projection,
        layer: markKey,
        matrixSet: projKey,
        style: "default",
        wrapX: true,
        tileGrid,
      }),
    });
  }

  // addLayers(map, [baseLayer, markLayer]);

  return new LayerGroup({
    properties: {
      id: `tdt_${layerType}_${projKey}`,
      name: `天地图${title}底图`,
    },
    layers: [baseLayer, markLayer],
  });
};
